﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DidaManager.Log;
using DidaManager.Native.Network;

namespace DidaManager.Native.RemoteTransmission
{
    public class ReqTransWebsocketData
    {
        [JsonProperty("token")]
        public string Token { get; set; }

        [JsonProperty("clientId")]
        public string ClientId { get; set; }

        [JsonProperty("params")]
        public string? Param { get; set; }

        [JsonProperty("method")]
        public string Method { get; set; }

        public ReqTransWebsocketData(string param)
        {
            Token = NetworkConfig.Instance.GetRemoteTransToken();
            ClientId = NetworkConfig.Instance.GetRemoteTransClientId(); 
            Param = param;
            Method = "thing.model.up_raw";
        }

        public static string GenerateClientId()
        {
            long timestampInTicks = DateTimeOffset.UtcNow.Ticks;
            long timestampInMicroseconds = timestampInTicks / 10; // Convert ticks to microseconds

            string clientId = timestampInMicroseconds.ToString();
            return clientId.Substring(Math.Max(0, clientId.Length - 8)); // Extract last 8 digits
        }
        public static string GenerateRandomNumberWithTimestamp()
        {
            Random random = new Random();
            int randomNumber = random.Next(1000, 9999); // 生成一个四位随机数

            long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); // 获取当前时间戳（毫秒）

            string result = $"{randomNumber}_{timestamp}"; // 将随机数和时间戳组合成字符串

            return result;
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }

        public static ReqTransWebsocketData? FromJson(string json)
        {
            return JsonConvert.DeserializeObject<ReqTransWebsocketData>(json);
        }
    }

    public class RspTransWebsocketData
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("msg")]
        public string Message { get; set; }

        public RspTransWebsocketData()
        {
            Code = string.Empty;
            Message = string.Empty;
        }

        public RspTransWebsocketData(string code, string message)
        {
            Code = code;
            Message = message;
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }

        public static RspTransWebsocketData? FromJson(string json)
        {
            try
            {
                return JsonConvert.DeserializeObject<RspTransWebsocketData>(json);
            }
            catch (JsonException ex)
            {
                LogManager.Debug($"Error deserializing JSON: {ex.Message}");
                return null;
            }
        }

        public bool IsSuccess()
        {
            return Code == "00000" && Message == "Success";
        }

        public bool IsValid()
        {
            try
            {
                int result = Int32.Parse(Code);
                return result == 0;
            }
            catch (FormatException)
            {
                LogManager.Debug($"Unable to parse '{Code}'");
            }
            return false;
        }

        public static bool CheckForCodeAndMessage(string jsonString)
        {
            try
            {
                JObject jsonObject = JObject.Parse(jsonString);
                bool containsCode = jsonObject.ContainsKey("code");
                bool containsMessage = jsonObject.ContainsKey("msg");

                return containsCode && containsMessage;
            }
            catch (Exception ex)
            {
                LogManager.Debug($"Error parsing JSON: {ex.Message}");
                return false;
            }
        }
    }

    class TabInfoData
    {
        [JsonProperty("name")]
        public string Name { get; set; } = string.Empty;
        [JsonProperty("title")]
        public string Title { get; set; } = string.Empty;
    }

    public class DirectData
    {
        [JsonProperty("id")]
        public string Id { get; set; } = string.Empty;

        [JsonProperty("portType")]
        public string PortType { get; set; } = string.Empty;

        [JsonProperty("serialParams")]
        public string SerialParams { get; set; } = string.Empty;

        [JsonProperty("serialPort")]
        public string SerialPort { get; set; } = string.Empty;

        [JsonProperty("serialPortNum")]
        public int SerialPortNum { get; set; } = 0;

        [JsonProperty("ip")]
        public string Ip { get; set; } = string.Empty;

        [JsonProperty("netPort")]
        public int NetPort { get; set; } = 0;

        [JsonProperty("function")]
        public string Function { get; set; } = string.Empty;

        [JsonProperty("data")]
        public string Data { get; set; } = string.Empty;

        [JsonProperty("dataLen")]
        public int DataLen { get; set; } = 0;

        public DirectData()
        {
            SerialParams    = "";
            SerialPort         = "";
            SerialPortNum = 0;
            Ip = "";
        }

        public void ToBase64()
        {
            DataLen = Data.Length;
            Data = Convert.ToBase64String(Encoding.UTF8.GetBytes(Data,0,DataLen));
        }
        public void FromBase64()
        {
            Data = Encoding.UTF8.GetString(Convert.FromBase64String(Data));
            if(Data.Length != DataLen)
            {
                Data = Encoding.UTF8.GetString(Convert.FromBase64String(Data));
            }
        }

        public static DirectData? FromJson(string json)
        {
            try
            {
                string payload = "payload";
                JObject jsonObject = JObject.Parse(json);

                // 使用 SelectToken 方法获取 payload 字段的值
                JToken? payloadToken = jsonObject.SelectToken(payload);

                // 检查 playloadToken 是否存在且是一个 JObject
                if (payloadToken != null && payloadToken is JObject)
                {
                    // 将 playloadToken 转换为 JObject
                    JObject payloadObject = (JObject)payloadToken;

                    // 将 playloadObject 转换为字符串
                    string payloadString = payloadObject.ToString();

                    // 使用 JsonConvert.DeserializeObject 方法将 payloadString 反序列化为 Info 对象
                    return JsonConvert.DeserializeObject<DirectData>(payloadString);
                }
                else
                {
                    LogManager.Debug("payload 字段不存在或不是一个对象。");
                    return null;
                }
            }
            catch (JsonException ex)
            {
                LogManager.Debug($"Error deserializing JSON: {ex.Message}");
                return null;
            }
        }
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

    class TransJsonManager
    {
        private static readonly TransJsonManager instance = new TransJsonManager();
        public static TransJsonManager Instance
        {
            get
            {
                return instance;
            }
        }
    }

}


